//index.js
//获取应用实例
var wxpay = require('../../utils/pay.js')
var app = getApp()

Page({
  data: {
    mallName: "",
    selList: '',
    confirmOrder: {},
    curAddressData: null,//收货地址
    allCoupon: [],//所有能用的优惠券
    curCoupon: null,//当前优惠券
    hasPay: false,
    storeid: app.globalData.storeId,
    cash: 0,
    choosecash: 2,
    diningSid: 0,
    myOrderData:{},
    tableNumber:""
  },

  toClasses:function(){
    wx.reLaunch({
      url: '/pages/classes-list/index',
    })
  },

  //获取餐桌设置
  getDiningTable: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Restaurant/GetDiningTable?id=" + app.globalData.diningSid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            tableNumber: res.data.Data.TableNumber
          })
        }
      },
    })
  },
 
  //获取账户余额
  getUserCash: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/UserCash/GetUserCash?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            cash: res.data.Data.Cash
          })
        }
      }
    })
  },

  onShow: function (e) {
    var c = wx.getStorageSync(this.data.selList);
    if (c) {
      this.setData({
        curCoupon: c
      })
      wx.clearStorageSync(this.data.selList);
    }
    this.confirmOrder();
    this.getUserCash()
  },

  onLoad: function (e) {
    var that = this;
    var selList = e.sl;
    var mallName = wx.getStorageSync('mallName')
    if (mallName){
      that.setData({ mallName: mallName });
    }
    that.setData({ selList: selList });
    that.getDiningTable();
  },

  selectCoupon: function () {
    wx.navigateTo({
      url: "/pages/member/coupon/index?st=1&sl=" + this.data.selList
    })
  },

  confirmOrder: function (e) {
    wx.showLoading();
    var that = this; 
    var said = 0;
    if (that.data.curAddressData) {
      said = that.data.curAddressData.SAId;
    }
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: said,
      Sid: app.globalData.diningSid
    }
    
    //初始化订单
    wx.request({
      url: app.globalData.host + '/api/order/SessionConfirmOrder',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0 && that.data.hasPay == false) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        }
        that.setData({
          hasPay: true
        });
        //订单确认成功
        if (res.data.Data == null){
          var confirm = []
        }else{
          var confirm = that.processImageHost(res.data.Data);
        }
        var selList = that.getSelList(confirm);
        if (selList){
          that.setData({ selList: selList})
          that.getValidCouponList(selList)
        }
        that.setData({
          confirmOrder: confirm,
        });
      }
    })
  },

  //请求优惠卷
  getValidCouponList: function (selList){
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/order/GetSessionValidCouponList',
      data: {
        selList: selList,
        uid: app.globalData.userInfo.Uid,
        sid: app.globalData.diningSid
      }, // 设置请求的 参数
      success: (res) => {
        if (res.data.Code != 0) {
          return;
        }
        that.setData({
          allCoupon: res.data.Data,
          curCoupon: res.data.Data[0] ? res.data.Data[0] : 0
        });
      }
    })
  },
  
  getSelList: function (cart) {
    var selList = '';
    var list = cart.StoreOrderList[0].StoreCartInfo.CartProductList;
    var cutList = cart.StoreOrderList[0].StoreCartInfo.CartFullCutList;
    var suitList = cart.StoreOrderList[0].StoreCartInfo.CartSuitList;
    var SendList = cart.StoreOrderList[0].StoreCartInfo.CartFullSendList;
    for (var i = 0; i < SendList.length; i++) {
      for (var j = 0; j < SendList[i].FullSendMainCartProductList.length; j++) {
        var curItem = SendList[i].FullSendMainCartProductList[j];
        if (curItem.IsSelected) {
          selList += curItem.OrderProductInfo.Type + '_' + curItem.OrderProductInfo.Pid + ','
        }
      }
    }
    for (var i = 0; i < list.length; i++) {
      if (list[i].IsSelected) {
        selList += list[i].OrderProductInfo.Type + '_' + list[i].OrderProductInfo.Pid + ','
      }

    }
    for (var i = 0; i < cutList.length; i++) {
      for (var j = 0; j < cutList[i].FullCutCartProductList.length; j++) {
        var curItem = cutList[i].FullCutCartProductList[j];
        if (curItem.IsSelected) {
          selList += curItem.OrderProductInfo.Type + '_' + curItem.OrderProductInfo.Pid + ','
        }
      }
    }
    for (var i = 0; i < suitList.length; i++) {
      var curItem = suitList[i];
      if (curItem.IsSelected) {
        selList += 1 + '_' + curItem.PmId + ','
      }
    }
    if (selList == '') { selList = '_' };
    return selList;
  },

  processImageHost: function (cart) {
    if (cart.StoreOrderList.length > 0) {
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartProductList.length; i++) {
        //主图
        cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].OrderProductInfo.ShowImg;
        if (cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList.length > 0) {
          for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList.length; j++) {
            //赠品图片
            cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList[j].ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList[j].ShowImg;
          }
        }
      }
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartFullCutList.length; i++) {
        for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList.length; j++) {
          cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg;
        }
      }
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartSuitList.length; i++) {
        for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList.length; j++) {
          cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg;
        }
      }
    }
    return cart;
  },

  createOrder: function (e) {
    var that = this;
    var cashNew = e.detail.value.cash || 0//余额
    var formGold = e.detail.value.gold || 0//金币
    var formRemark = e.detail.value.remark || ""//备注
    var myOrderData = that.data.myOrderData//选择优惠券
    var curCoupon = {}//默认优惠券
    var curCouponId = 0//优惠券id
    var curCouponMoney = 0//优惠券金额
    if (JSON.stringify(myOrderData) != "{}") {
      curCoupon = myOrderData//优惠券
      curCouponId = curCoupon.couponid
      curCouponMoney = curCoupon.money
    } else {
      if (that.data.curCoupon) {
        curCoupon = that.data.curCoupon//优惠券
        curCouponId = curCoupon.CouponId
        curCouponMoney = curCoupon.Money
      }
    }
    var PayCreditPrice = that.data.confirmOrder.PayCreditPrice//积分价格
    if (formGold) {
      var PayCredits = formGold / 100 * PayCreditPrice//积分金额
    } else {
      var PayCredits = 0
    }
    var AllOrderAmount = that.data.confirmOrder.AllOrderAmount//订单总额
    var AllFullCut = that.data.confirmOrder.AllFullCut//满减
    var countMoney = parseFloat(curCouponMoney) + parseFloat(AllFullCut) + parseFloat(PayCredits) + parseFloat(cashNew)//优惠总和
    var uid = app.globalData.userInfo.Uid // 用户登录 uid
    if (!uid) {
      wx.showModal({
        title: '提示',
        content: '获取用户信息失败',
        showCancel: false
      })
      return;
    }
    wx.showLoading();
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      Sid: app.globalData.diningSid,
      SaId: 0,//配送地址id
      SelList: that.data.selList,//选中的购物车项键列表
      PayCreditCount: parseFloat(formGold),//支付积分
      PayCash: parseFloat(cashNew),//余额支付
      CouponIdList: curCouponId,//客户已经激活的优惠劵
      CouponSNList: '',//客户还未激活的优惠劵
      FullCut: that.data.confirmOrder.AllFullCut,//验证满减金额
      BuyerRemark: formRemark //备注
    }
    wx.request({
      url: app.globalData.host + '/api/order/SubmitSessionOrder',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        console.log(res)
        wx.hideLoading();
        if (res.data.Code != 0) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        } else {
            // 下单成功，跳转到订单详情支付界面
            app.globalData.diningSid = 0
            var oid = res.data.Data;
            wxpay.wxpay(app, oid, "/pages/order-list/index");
        }
      }
    })
  },

  initShippingAddress: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/user/GetDefaultShipAddress',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: (res) => {
        if (res.data.Code == 0) {
          that.setData({
            curAddressData: res.data.Data
          });
        }
      }
    })
  },

  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/index?said=0"
    })
  },

  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },

  selectCoupon: function () {
    wx.navigateTo({
      url: "/pages/member/coupon/index?st=3&sl=" + this.data.selList
    })
  },

  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    var that = this;
    wx.showLoading({
      title: '正在刷新',
      success: function () {
        that.confirmOrder()
      }
    })
    wx.stopPullDownRefresh();
  }
})
